import React, {
    PureComponent
} from 'react';

import {
    View,
    Text,
    ScrollView,
    Dimensions,
    StyleSheet
} from 'react-native';

import {
    Actions
} from 'react-native-router-flux';

import {
    Tip,
    File,
    Choose,
    Loading
} from './../../components';

import {
    PhotoItem
} from '../../types/types';

import Ajax from './../../http';

import * as CONST from './../../const';

import parseUrl from './../../utils/parseUrl';

import connect from './../../utils/connect';

import userAction from './../../state/actions/user';
import * as userTypes from './../../state/types/user';

interface Photo {
    url: string,
    photoId?: string,
    attachId: string,
    isAvatar?: boolean
}

interface State {
    photos?: Array<Photo>
}

interface Props {
    user: any,
    avatar: string,
    userActions: any
}

const {
    width
} = Dimensions.get('window');

const contentWidth = width - 48;
const itemWidth = contentWidth / 3;


const checkHttp = (url: string) => (
    /http/.test(url)
)

@connect([`user`], {
    userActions: userAction
})
class Photo extends PureComponent <Props, State> {
    constructor(props:Props) {
        super(props);
        this.state = {
            photos: []
        }
    }

    static defaultProps = {
        avatar: ``,
        userActions:{}
    }

    static getDerivedStateFromProps(
        nextProps: Props,
        prevState: State
    ) {
        const {
            user
        } = nextProps;

        const {
            loginUser
        } = user;

        const {
            photos = []
        } = loginUser;

        const {
            length = 0
        } = prevState.photos || [];

        if (photos.length && !length) {
            return {
                photos: photos.filter((item:any) => (
                    !!item.attachId
                ))
            }
        }

        return null;
    }

    get userActions() {
        const {
            userActions
        } = this.props;

        return userActions;
    }

    componentDidMount() {
        this.userActions[
            userTypes.loginUser
        ]();
    }

    get items() {
        return Array.from({length: 12
        })
    }

    _onFileChange = async (item:any) => {
        const {
            photos = []
        } = this.state;

        Loading.show(`Uploading..`);

        try {
            const {
                id
            } = await Ajax.uploadImage(
                item.path
            ) as any;

            const _item = {
                attachId: id,
                url: item.path,
                isAvatar: photos.length <= 0
            } as Photo;

            photos.push(_item);

            this.setState({
                photos: [...photos]
            })
        }
        catch (e) {
            Tip.warm({
                message: e.message
            })
        }

        Loading.close();
    }

    onDelete = async (i: number) => {
        const {
            photos=[]
        } = this.state;

        const {
            photoId
        } = photos[i];

        Loading.show();
        try {
            if (!!photoId) {
                await this.userActions[
                    userTypes.deleteUserPhoto
                ](photoId)
            }
            photos.splice(i, 1);
            this.setState({
                photos: [...photos]
            })
        }
        catch (e) {
            Tip.warm({
                message: e.message
            })
        }
        Loading.close();
    }

    onSetAvatar = (i: number) => {
        const {
            photos=[]
        } = this.state;

        photos.forEach(item => (
            item.isAvatar = false
        ))

        photos[i].isAvatar = true;

        this.setState({
            photos: [...photos]
        })
    }

    get disabled() {
        const {
            photos=[]
        } = this.state;
        return !photos.length
    }

    get avatarItem() {
        const {
            photos=[]
        } = this.state;
        return photos.find(({isAvatar}) => isAvatar) || {} as PhotoItem;
    }

    private renderItem = (_item:any, i:number) => {
        const {
            photos=[]
        } = this.state;
        const {
            url,
            isAvatar
        } = photos[i] || {} as Photo;

        const _url = checkHttp(url) ? parseUrl(url):url;

        return (
            <View key={i} style={styles.photoItem}>
                <File onChange={this._onFileChange}>
                    <Choose
                        url={_url}
                        isAvatar={isAvatar}
                        onDelete={() => this.onDelete(i)}
                        onSetAvatar={() => this.onSetAvatar(i)}
                    />
                </File>
            </View>
        )
    }

    public onSubmit = async () => {
        const {
            photos=[]
        } = this.state;

        const attachIds = (
            photos.map(item => (
                item.attachId
            ))
        )

        const {
            attachId
        } = this.avatarItem;

        const _para = {
            avatarAId: attachId,
            attachIds: attachIds
        }

        Loading.show();

        try {
            await this.userActions[
                userTypes.bindUserPhoto
            ](_para);
            this.onSuccess();
        }
        catch (e) {
            Tip.warm({
                message: e.message
            })
        }
        Loading.close();
    }

    private onSuccess = () => {
        Actions.pop();
        Tip.success({
            message:`Save successfully.`
        })
    }

    render() {
        return (
            <View style={styles.pageContainer}>
                <ScrollView style={styles.container}>
                    <View style={styles.content}>
                        {this.items.map(this.renderItem)}
                    </View>
                </ScrollView>
            </View>
        )
    }
}

export default Photo;

const styles = StyleSheet.create({
    pageContainer: {
        flex:1,
        paddingBottom:16,
        paddingHorizontal:16
    },
    container:{
        paddingHorizontal:8,
        backgroundColor:`#fff`,
        borderBottomLeftRadius:8,
        borderBottomRightRadius:8
    },
    content: {
        flexWrap: `wrap`,
        flexDirection: `row`
    },
    photoItem: {
        width: itemWidth,
        height:itemWidth,
        marginBottom: 6,
        paddingVertical:4,
        paddingHorizontal:4,
        alignItems: `center`,
        justifyContent: `center`
    },
    lineStyle:{
        left:0,
        right:0,
        height:60,
        position:`absolute`,
        backgroundColor:CONST.color
    },
    doneText:{
        fontSize:18,
        color:`#fff`,
        fontWeight:`bold`
    },
    doneStyle:{
        height:`100%`,
        paddingLeft:16,
        justifyContent:`center`
    }
}) as any